package com.example.caoh.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;



/**
 * @author wuxi
 */
public class ElsSearchHelper {
	private final static Logger log = LoggerFactory.getLogger(ElsSearchHelper.class);
	private final static String ELS_URL;
	static {
		ELS_URL = Config.getConfig("ELS_URL");
	}

	public static ElsResult search(ElsQuery query) throws Exception {
		String jsonData = query.toString();
		log.info(String.format("%s/%s/_search,data=%s", ELS_URL, query.getIndex(), jsonData));
		String ret = ElsRequest.search(ELS_URL, query.getIndex(), jsonData);
		JSONObject obj = JSONObject.parseObject(ret);
		ElsResult result = new ElsResult();
		JSONObject hits = obj.getJSONObject("hits");
		result.setTook(obj.getLong("took"));
		result.setTotal(hits.getLong("total"));
		if(obj.getJSONObject("aggregations")!=null){
			JSONObject totalData = obj.getJSONObject("aggregations");
			result.setSumData(totalData);
		}
		JSONArray array = hits.getJSONArray("hits");
		for (int i = 0, j = array.size(); i < j; i++)
			result.addData(array.getJSONObject(i).getJSONObject("_source"));
		
		if(result.getDatas().size()==1){
			if(result.getDatas().get(0).get("index")!=null){
				result.getDatas().clear();
				result.setTotal(0l);
			}
		}
		return result;
	}
	
	
	public static ElsResult searchShould(ElsQuery query) throws Exception {
        String jsonData = query.toString();
        JSONObject queryJson=JSONObject.parseObject(jsonData);
        
        
        //如果有should，则更改查询结构
        JSONArray should=new JSONArray();
        if(queryJson.getJSONObject("query").getJSONObject("bool").containsKey("should")){
            
           should= queryJson.getJSONObject("query").getJSONObject("bool").getJSONArray("should");
           queryJson.getJSONObject("query").getJSONObject("bool").remove("should");
           
           
           JSONArray must=new JSONArray();
           if(queryJson.getJSONObject("query").getJSONObject("bool").containsKey("must")){
               must= queryJson.getJSONObject("query").getJSONObject("bool").getJSONArray("must");
               queryJson.getJSONObject("query").getJSONObject("bool").remove("must");
           }
           
           JSONArray newMust =new JSONArray();
           queryJson.getJSONObject("query").getJSONObject("bool").put("must", newMust);
           
           JSONObject newBoolShould=new JSONObject();
           newBoolShould.put("bool", new JSONObject());
           newBoolShould.getJSONObject("bool").put("should", should);
           
           JSONObject newBoolMust=new JSONObject();
           newBoolMust.put("bool", new JSONObject());
           newBoolMust.getJSONObject("bool").put("must", must);
           
           if(must.size()>0){
               newMust.add(newBoolMust);
           }
           newMust.add(newBoolShould);
        }
        jsonData=queryJson.toString();
        
        
        log.info(String.format("%s/%s/_search,data=%s", ELS_URL, query.getIndex(), jsonData));
        String ret = ElsRequest.search(ELS_URL, query.getIndex(), jsonData);
        JSONObject obj = JSONObject.parseObject(ret);
        ElsResult result = new ElsResult();
        JSONObject hits = obj.getJSONObject("hits");
        result.setTook(obj.getLong("took"));
        result.setTotal(hits.getLong("total"));
        if(obj.getJSONObject("aggregations")!=null){
            JSONObject totalData = obj.getJSONObject("aggregations");
            result.setSumData(totalData);
        }
        JSONArray array = hits.getJSONArray("hits");
        for (int i = 0, j = array.size(); i < j; i++)
            result.addData(array.getJSONObject(i).getJSONObject("_source"));
        
        if(result.getDatas().size()==1){
            if(result.getDatas().get(0).get("index")!=null){
                result.getDatas().clear();
                result.setTotal(0l);
            }
        }
        return result;
    }

	public static ElsResult searchGroup(ElsQuery query, String key, String value) throws Exception {
		String jsonData = query.toString();
		log.info(String.format("%s/%s/_search?search_type=count,data=%s", ELS_URL, query.getIndex(), jsonData));
		String ret = ElsRequest.search(ELS_URL, query.getIndex(), jsonData);
		JSONObject obj = JSONObject.parseObject(ret);
		ElsResult result = new ElsResult();
		JSONArray array = obj.getJSONObject("aggregations").getJSONObject("dicts").getJSONArray("buckets");
		result.setTotal(array.size() + 0l);
		result.setTook(obj.getLong("took"));
		JSONObject data;
		for (int i = 0, j = array.size(); i < j; i++) {
			data = new JSONObject();
			data.put(key, array.getJSONObject(i).get("key"));
			data.put(value, array.getJSONObject(i).getJSONObject("names").getJSONObject("hits").getJSONArray("hits")
					.getJSONObject(0).getJSONObject("_source").getString(value));
			result.addData(data);
		}
		return result;
	}
	
	public static String searchGroup(ElsQuery query) throws Exception {
		String jsonData = query.toString();
		log.info(String.format("%s/%s/_search?search_type=count,data=%s", ELS_URL, query.getIndex(), jsonData));
		return ElsRequest.search(ELS_URL, query.getIndex(), jsonData);
	}
	

	public static JSONObject get(String id, ElsIndex index) throws Exception {
		String ret = ElsRequest.get(ELS_URL, index, id);
		return (JSONObject) JSONObject.toJSON(ret);
	}

}
